<script setup>
import GoodsItem from '@/components/GoodsItem.vue'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getProListApi } from '@/api/product'

const route = useRoute()
const router = useRouter()

const page = ref(1)
const proList = ref([])
const activeType = ref('all')
const sortPrice = ref(0)

const querySearch = computed(() => {
  // 返回 搜索框内容，判断 是否为undefined，为undefined则返回默认值
  return route.query.search !== undefined ? route.query.search : '请搜索你想要的商品'
})

const getSearchList = async () => {
  const { data: { list } } = await getProListApi({
    sortType: activeType.value,
    sortPrice: sortPrice.value,
    categoryId: route.query.categoryId,
    goodsName: route.query.search, // 不能为querySearch.value，因为从分类中进入的该值为自定义的字符串，接口无法返回数据
    page: page.value
  })
  proList.value = list.data
}

const changeSort = (index) => {
  activeType.value = index === 0 ? 'all' : index === 1 ? 'sales' : 'price'
  getSearchList()
  if (sortPrice.value === 0 && index === 2) {
    sortPrice.value = 1
  } else {
    sortPrice.value = 0
  }
}

onMounted(() => {
  getSearchList()
})
</script>

<template>
  <div class="search">
    <van-nav-bar fixed title="商品列表" left-arrow @click-left="router.replace('/search')"/>

    <van-search
      readonly
      shape="round"
      background="#ffffff"
      v-model="querySearch"
      show-action
      @click="router.replace('/search')"
    >
      <template #action>
        <van-icon class="tool" name="apps-o"/>
      </template>
    </van-search>

    <!-- 排序选项按钮 -->
    <div class="sort-btns">
      <div class="sort-item" @click="changeSort(0)" :class="{ active: activeType === 'all' }">综合</div>
      <div class="sort-item" @click="changeSort(1)" :class="{ active: activeType === 'sales' }">销量</div>
      <div class="sort-item" @click="changeSort(2)" :class="{ active: activeType === 'price' }">价格</div>
    </div>

    <div class="goods-list">
      <GoodsItem v-for="item in proList" :key="item.goods_id" :item="item"></GoodsItem>
    </div>
  </div>
</template>

<style lang="less" scoped>
.search {
  padding-top: 46px;

  ::v-deep .van-icon-arrow-left {
    color: #333;
  }

  .tool {
    font-size: 24px;
    height: 40px;
    line-height: 40px;
  }

  .sort-btns {
    display: flex;
    height: 36px;
    line-height: 36px;

    .sort-item {
      text-align: center;
      flex: 1;
      font-size: 16px;

      &.active {
        color: #ff6700;
        border-bottom: 2px solid #ff6700;
      }
    }
  }
}

// 商品样式
.goods-list {
  background-color: #f6f6f6;
}
</style>

<script>
export default {
  name: 'SearchList'
}
</script>
